package com.talkweb.securitycamera.data.hadoopFile;

import com.talkweb.securitycamera.common.constans.FileType;
import com.talkweb.securitycamera.common.interfaces.dataprocess.FileCallback;
import com.talkweb.securitycamera.utils.TimeUtils;
import ohos.app.Context;

import java.io.*;

/**
 * 用来写入视频与图片的类
 * <p>
 * class to save image and video files
 *
 * @author : frank
 * @date : 2021/2/1 14:47
 */
public class SimpleFileWriter implements IFileWriter {

    private BufferedOutputStream out;

    private Context context;

    private String hadoopFilePath;

    private long writeCount = 0;

    private static final int MAX_CAP = 2;

    private FileType fileType;

    private FileCallback fileCallback;

    private IMemoryPolicy pocily;

    public void setFileCallback(FileCallback fileCallback) {
        this.fileCallback = fileCallback;
    }

    /**
     * @param context
     * @param fileType 文件类型,包括视频与图片
     */
    SimpleFileWriter(Context context, FileType fileType, IMemoryPolicy pocily) {
        this.pocily = pocily;
        this.context = context;
        this.fileType = fileType;
        generateOutputFile(context, fileType);
    }

    private void generateOutputFile(Context context, FileType fileType) {
        String suffix = fileType == FileType.FILE_TYPE_IMAGE ? ".jpg" : ".mp4";
        File mediaDirectory = MediaDirectoryProvider.provideMediaDirectory(context, fileType);
        hadoopFilePath = mediaDirectory.getAbsolutePath() + File.separator + TimeUtils.getTimeYYYYMMddHHmmss(System.currentTimeMillis()) + suffix;
        try {
            out = new BufferedOutputStream(new FileOutputStream(hadoopFilePath, true));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void write(byte[] data) {
        try {
            if (pocily != null && pocily.isMemInfoOut()) {
                //内存不足 需要清理
                pocily.cleanMemory(context,fileType);
            }
            out.write(data);
            out.flush();
            writeCount += data.length;
            if (fileType == FileType.FILE_TYPE_IMAGE) {
                recycle();
                return;
            }
            if (isCaptrueOut(writeCount)) {
                recycle();
                generateOutputFile(context, fileType);
            }
        } catch (Exception e) {
            e.printStackTrace();
            recycle();
        }
    }


    private void recycle() {
        if (out != null) {
            try {
                out.close();
                writeCount = 0;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        out = null;
        fileCallback.onDataChanged(fileType);
    }

    private boolean isCaptrueOut(long count) {
        long G = count / 1024 / 1024 / 1024;
        if (G >= MAX_CAP) {
            return true;
        }
        return false;
    }
}
